<?php

namespace app\controllers\h5\mini;

use app\controllers\h5\base\H5Controller;
use app\controllers\wx\services\Wx;
use app\models\system\SetCertBg;
use app\models\system\SetQrcode;
use app\models\system\SetWx;
use app\models\user\User;
use app\models\user\UserLevel;
use app\util\Qrcode;
use app\util\Request;
use yii\imagine\Image;

class MiniQrcodeController extends H5Controller
{
    public function actionGetQrcode()
    {
        $set = SetWx::getLastOne(false);

        // $qrcodeSet = SetQrcode::getLastOne();

        // var_dump($qrcodeSet->width);exit;

        $scene = $this->post('scene', $this->user->id);
        // 页面 page，例如 pages/index/index，根路径前不要填加 /
        // $page = $this->post('page', 'sub_main/pages/user/login/index');

        $base = \Yii::$app->getBasePath();
        $path = $base . '/web/qrcode/referrer/' . $scene . '.jpg';
        // $path = $base . '/web/qrcode/referrer/' . $scene . '.jpg';

        if (!file_exists($path)) {
            // get
            // $getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$set->app_id}&secret={$set->app_secret}";
            // $result = Request::get($getAccessToken);
            $access_token = Wx::getAccessToken();

            // post
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            // $result = Request::post($url, json_encode(['scene' => $scene, 'page' => $page]));
            $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 375])); // 最小也是280
            // $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 280, 'is_hyaline' => true]));

            // todo 这里token可能过期

            // var_dump($result);exit;

            $dir = dirname($path);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }

            // wx qrcode
            file_put_contents($path, $result);

            // sleep(1);
        }

        // list
        $list = [];
        $name = '/qrcode/referrer/' . $scene . '.jpg';
        // $name = '/qrcode/referrer/' . $scene . '.jpg';

        // var_dump($path);exit;

        // if (file_exists($path)) {
        //     Image::thumbnail(
        //         $path,
        //         120,
        //         120
        //     )->save($path, ['quality' => 100]);
        // }

        $set = SetQrcode::getLastOne();
        // $nickname = User::find()
        //     ->where(['id' => $this->user->id])
        //     ->select(['nickname'])
        //     ->scalar();
        // if ($nickname) {
        //     $nickname = base64_decode($nickname);
        // } else {
        //     $nickname = '';
        // }
        // $length = 4;
        // if (mb_strlen($nickname) > $length) {
        //     $nickname = mb_substr($nickname, 0, $length) . '...';
        // }

        if ($set['images'] && count($set['images']) > 0) {
            foreach ($set['images'] as $item) {

                $poster = $item['path'];
                $real = '/qrcode/referrer/' . $scene . '-' . $item['id'] . '.jpg';
                // $real = '/qrcode/referrer/' . $scene . '-' . $item['id'] . '.jpg';
                // Qrcode::setPoster($name, $poster, $real, [43, 285]);

                // var_dump($name, $real);exit;



                // 这里用了缩小, 并且处理了 位置 (375 - 120) / 2
                // Qrcode::setPoster($name, $poster, $real, [127, 370], [120, 120]);
                // Qrcode::setPoster($name, $poster, $real, [$left, $h1]);

                $b = \Yii::$app->getBasePath() . '/web';
                $thum = '/qrcode/referrer/' . $scene . '-thum.jpg';

                // 先生成缩略图
                Image::thumbnail(
                    $b . $name,
                    $set->width * 2,
                    $set->height * 2
                )->save($b . $thum, ['quality' => 50]);

                // 再用缩略图打水印
                Qrcode::setPoster($thum, $poster, $real, [$set->left * 2, $set->top * 2]);

                // 文字
                // Qrcode::setText($real, 'ID:' . $this->user->id, '',
                //     [$set->left * 2 + 10, ($set->top + $set->height) * 2 + 50], 36,'#ffffff');

                // 处理小程序缓存
                array_push($list, $real . '?t=' . time());

            }
        }


        $data = [
            'list' => $list,
            'id' => $scene,
        ];

        return $this->successEncode($data);
    }

    // 会员证书
    public function actionGetCert()
    {
        // 会员信息
        $user = User::find()
            ->where(['id' => $this->user->id])
            ->with(['level0'])
            ->asArray()
            ->one();

        if ($user['level'] < UserLevel::$keys['vip1']) {
            return $this->fail('您还没有获得相应证书资格!');
        }

        // var_dump($user);exit;

        $name = '/cert/' . $this->user->id . '.png';

        $base = \Yii::$app->getBasePath();
        $path = $base . '/web' . $name;

        // var_dump($path);exit;

        $set = SetCertBg::getLastOne();
        $bg = $set['images'][0]['path'];
        $bg = \Yii::$app->getBasePath() . '/web' . $bg;

        // 先生成缩略图
        Image::thumbnail(
            $bg,
            750,
            1040
        )->save($path, ['quality' => 100]);


        if ($user['nickname']) {
            $user['nickname'] = base64_decode($user['nickname']);

            // 截取
            $user['nickname'] = mb_substr($user['nickname'], 0, 11, 'UTF-8');
        }

        $color = '#000000';
        $left = 258;

        Qrcode::setText($name, $user['nickname'], '', [$left, 380], 24, $color);
        Qrcode::setText($name, $user['mobile'], '', [$left, 433], 24, $color);
        Qrcode::setText($name, $user['level0']['display'], '', [$left, 500], 24, $color);

        $top = 782;
        $date = strtotime($user['create_time']);
        Qrcode::setText($name, date('Y', $date), '', [350, $top], 20, $color);
        Qrcode::setText($name, date('m', $date), '', [473, $top], 20, $color);
        Qrcode::setText($name, date('d', $date), '', [553, $top], 20, $color);

        return $this->successEncode([
            'list' => [$name . '?t=' .time()]
        ]);
    }
}